package com.zhixing.common.config;

import com.zhixing.common.converter.StringToEnumConverterFactory;
import com.zhixing.common.interceptor.UserInfoInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@ConditionalOnClass(DispatcherServlet.class)
@RequiredArgsConstructor
public class MvcConfig implements WebMvcConfigurer {

    private final ExcludePathsProperties excludePathsProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePaths = excludePathsProperties.getExcludePaths().stream()
                .map(path -> path.substring(path.substring(1).indexOf("/") + 1))
                .toList();
        registry.addInterceptor(new UserInfoInterceptor()).excludePathPatterns(excludePaths);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new StringToEnumConverterFactory());
    }
}
